<template>
  <div class="borrow-container">
    <!-- 页面标题和统计 -->
    <div class="header">
      <h2>设备借用</h2>
      <div class="stats">
        <el-tag type="info" class="stat-tag">
          总设备: {{ totalEquipment }}
        </el-tag>
        <el-tag type="success" class="stat-tag">
          可用设备: {{ availableEquipment }}
        </el-tag>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-container">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索设备名称"
        clearable
        class="search-input"
        :prefix-icon="Search"
      />
      <el-select
        v-model="statusFilter"
        placeholder="设备状态"
        clearable
        class="filter-select"
      >
        <el-option label="空闲" value="空闲" />
        <el-option label="使用中" value="使用中" />
        <el-option label="维修中" value="维修中" />
      </el-select>
      <el-button type="primary" @click="refreshEquipmentList">
        刷新
      </el-button>
    </div>

    <!-- 可借用设备列表 -->
    <el-table 
      :data="filteredEquipmentList" 
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="id" label="设备ID" width="80" />
      <el-table-column prop="name" label="设备名称" width="200" />
      <el-table-column prop="description" label="设备描述" min-width="200" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTagType(row.status)">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="update_time" label="更新时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.update_time) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" align="center">
        <template #default="{ row }">
          <el-button
            type="primary"
            size="small"
            :disabled="row.status !== '空闲'"
            @click="handleBorrow(row)"
          >
            {{ row.status === '空闲' ? '借用' : '不可借用' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 借用申请对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="设备借用申请"
      width="500px"
    >
      <el-form 
        :model="form" 
        :rules="rules"
        ref="formRef"
        label-width="100px"
      >
        <el-form-item label="设备名称">
          <el-input v-model="selectedEquipment.name" disabled />
        </el-form-item>
        <el-form-item label="设备描述">
          <el-input v-model="selectedEquipment.description" disabled />
        </el-form-item>
        <el-form-item label="使用目的" prop="purpose">
          <el-input
            v-model="form.purpose"
            type="textarea"
            :rows="3"
            placeholder="请说明设备使用目的"
          />
        </el-form-item>
        <el-form-item label="预计使用时长" prop="duration">
          <el-select v-model="form.duration" placeholder="请选择">
            <el-option label="1小时" value="1小时" />
            <el-option label="半天" value="半天" />
            <el-option label="1天" value="1天" />
            <el-option label="3天" value="3天" />
            <el-option label="1周" value="1周" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmBorrow"
            :loading="submitting"
          >
            确认借用
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import axios from 'axios'

// 响应式数据
const searchKeyword = ref('')
const statusFilter = ref('')
const loading = ref(false)
const dialogVisible = ref(false)
const submitting = ref(false)

// 表单引用
const formRef = ref()

// 数据列表
const equipmentList = ref([])
const selectedEquipment = ref({})

// 过滤后的设备列表
const filteredEquipmentList = computed(() => {
  let filtered = equipmentList.value
  
  if (searchKeyword.value) {
    filtered = filtered.filter(item => 
      item.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }
  
  if (statusFilter.value) {
    filtered = filtered.filter(item => item.status === statusFilter.value)
  }
  
  return filtered
})

// 借用表单
const form = reactive({
  purpose: '',
  duration: ''
})

const rules = reactive({
  purpose: [
    { required: true, message: '请说明使用目的', trigger: 'blur' },
    { min: 5, max: 200, message: '使用目的应在5-200个字符之间', trigger: 'blur' }
  ],
  duration: [
    { required: true, message: '请选择预计使用时长', trigger: 'change' }
  ]
})

// 获取设备列表
const getEquipmentList = async () => {
  loading.value = true
  try {
    const response = await axios.get('http://localhost:8080/api/v1/admin/equStatus')
    if (response.data.code === 200) {
      equipmentList.value = response.data.data
    } else {
      ElMessage.error('获取设备列表失败')
    }
  } catch (error) {
    console.error('获取设备列表失败:', error)
    ElMessage.error('网络请求失败')
  } finally {
    loading.value = false
  }
}

// 刷新设备列表
const refreshEquipmentList = () => {
  getEquipmentList()
}

// 处理设备借用
const handleBorrow = (equipment) => {
  selectedEquipment.value = equipment
  dialogVisible.value = true
  // 重置表单
  form.purpose = ''
  form.duration = ''
}

// 确认借用
const confirmBorrow = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      
      try {
        const userId = localStorage.getItem('userId')
        const response = await axios.post('http://localhost:8080/api/v1/stu/borrow', {
          equipmentId: selectedEquipment.value.id,
          userId: parseInt(userId),
          action: '使用',
          remark: form.purpose  // 将使用目的作为备注信息提交
        })
        
        if (response.data.code === 200) {
          ElMessage.success('设备借用申请提交成功')
          dialogVisible.value = false
          getEquipmentList() // 刷新设备列表
        } else {
          ElMessage.error(response.data.message || '借用申请失败')
        }
      } catch (error) {
        console.error('借用申请失败:', error)
        ElMessage.error('网络请求失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const statusMap = {
    '空闲': 'success',
    '使用中': 'warning',
    '维修中': 'danger',
    '报废': 'info'
  }
  return statusMap[status] || 'default'
}

// 统计数据
const totalEquipment = computed(() => equipmentList.value.length)
const availableEquipment = computed(() => 
  equipmentList.value.filter(item => item.status === '空闲').length
)

// 组件挂载时获取数据
onMounted(() => {
  getEquipmentList()
})
</script>

<style scoped>
.borrow-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.stats {
  display: flex;
  gap: 10px;
}

.stat-tag {
  padding: 8px 16px;
}

.search-container {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.filter-select {
  width: 150px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .stats {
    flex-wrap: wrap;
  }
  
  .search-container {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input,
  .filter-select {
    width: 100%;
  }
}
</style>